/**
 * @file AppAppication.java
 * @create 下午4:00:30
 * @author CX
 * @description 全局应用类
 */
package cn.edu.hstc.wm;

import android.app.Application;
import android.content.Context;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.AsyncTask;
import android.os.Build;
import android.os.StrictMode;
import android.util.Log;
import android.widget.Toast;
import cn.edu.hstc.wm.bean.User;
import cn.edu.hstc.wm.exception.AppException;
import cn.edu.hstc.wm.https.HttpUtils;
import cn.edu.hstc.wm.receiver.NetCheckReceiver;
import cn.edu.hstc.wm.service.AppConfigService;
import cn.edu.hstc.wm.service.UserService;
import cn.edu.hstc.wm.utils.LogUtil;

import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.MKGeneralListener;
import com.baidu.mapapi.map.MKEvent;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;

/**
 * @ClassName: AppApplication
 * @Description: 全局应用程序类,全局上下文
 * 
 * @ModificationHistory
 */
public class AppApplication extends Application {
	public static final String TAG = "AppAppication";

	private static AppApplication mInstance;

	/** 当前用户 */
	private User mUser;

	/** 网络状态监听器 */
	private NetCheckReceiver mNetCheckReceiver;

	/** 网络状态 */
	public static int netWorkStatus = Constants.NET_TYPE_DISABLE;

	/** 登录状态 */
	private static boolean mLoginStatus = false;

	/** 百度地图管理 */
	public BMapManager mBMapManager = null;
	public boolean m_bKeyRight = true;

	public void onCreate() {
		super.onCreate();
		mInstance = this;
		Log.d(TAG, "onCreate");
		initApp();
	}

	public void onLowMemory() {
		super.onLowMemory();
		Log.d(TAG, "onLowMemory");
	}

	public void onTerminate() {
		super.onTerminate();
		Log.d(TAG, "onTerminate");
		// 停止监听广播
		if (mNetCheckReceiver != null) {
			unregisterReceiver(mNetCheckReceiver);
		}
	}

	/**
	 * 结束该应用
	 */
	public static void exit() {
		AppManager.getManager().finishAll();
		// 结束当前的进程
		android.os.Process.killProcess(android.os.Process.myPid());
	}

	/**
	 * 初始化app
	 */
	@SuppressWarnings("unused")
	private void initApp() {

		// 使用默认的异常处理器来处理为捕获到的Exception
		AppException.getInstance().init(this);

		// 注册网络状态监听器
		registerCheckNetStatus();

		// 检查网络状态
		checkNetStatus();

		// 初始化App 登录信息
		// mLoginStatus = login();

		// 设置图片加载器的默认配置信息
		if (Constants.DEVELOPER_MODE && Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
			StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectAll().penaltyDialog().build());
			StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll().penaltyDeath().build());
		}
		initImageLoader(getApplicationContext());

		// 初始化百度地圖
		// TODO initEngineManager(getApplicationContext());

	}

	/**
	 * 返回全局唯一的Application实例
	 * 
	 * @return
	 */
	public static AppApplication getInstance() {
		return mInstance;
	}

	/**
	 * 初始化一个ImageLoader全局的实例,
	 */
	public static void initImageLoader(Context context) {
		// 实例化配置信息
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context).threadPriority(Thread.NORM_PRIORITY - 2)
				.denyCacheImageMultipleSizesInMemory().discCacheFileNameGenerator(new Md5FileNameGenerator())
				.tasksProcessingOrder(QueueProcessingType.LIFO)// .writeDebugLogs()
																// // Remove
				.memoryCacheExtraOptions(128, 128)

				.build();
		// 实例化单例模式的ImageLoader
		ImageLoader.getInstance().init(config);
	}

	/**
	 * 检查网络状态
	 */
	private void checkNetStatus() {
		// 网络都不可用
		if (!HttpUtils.isMobileDataEnable(this) && !HttpUtils.isWifiDataEnable(this)) {
			netWorkStatus = Constants.NET_TYPE_DISABLE;
		}
		// 网络可用
		else {
			netWorkStatus = Constants.NET_TYPE_ENABLE;
		}
		LogUtil.i(TAG, "net status = " + netWorkStatus);
	}

	/** 动态注册网络状态监听器 */
	private void registerCheckNetStatus() {
		IntentFilter filter = new IntentFilter(NetCheckReceiver.NET_CHANGE_ACTION);
		filter.setPriority(android.content.IntentFilter.SYSTEM_HIGH_PRIORITY - 1);
		mNetCheckReceiver = new NetCheckReceiver();
		registerReceiver(mNetCheckReceiver, filter);
	}

	/**
	 * 取得保存的用户
	 * 
	 * @return
	 */
	public User getLoginUser() {
		try {
			return AppConfigService.getUserFromConf(this);

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 用户登录
	 */
	public boolean login() {
		try {
			if (getLoginUser() != null && loginVerify(getLoginUser()) != null) {
				mLoginStatus = true;
				return true;
			}
		} catch (AppException e) {
			e.printStackTrace();
			return false;
		} catch (InterruptedException e) {
			e.printStackTrace();
			return false;
		}
		return false;
	}

	/**
	 * 注销登录
	 */
	public void logout() {
		mUser = null;
		mLoginStatus = false;
	}

	/**
	 * 是否已经登录
	 * 
	 * @return
	 */
	public boolean isLogin() {
		return mLoginStatus;
	}

	/**
	 * 校验用户登录,
	 * 
	 * @param user
	 * @return 如果成功则返回一个详细包装的User;如果失败则返回null
	 * @throws InterruptedException
	 */
	public User loginVerify(User user) throws AppException, InterruptedException {
		// 登录过程
		// Thread.sleep(500);
		// 返回一个User
		if (UserService.verifyUser(user)) {
			// new LoginTask().execute(user);
			mUser = UserService.login(user);
		}
		return mUser;
	}

	/**
	 * 保存用户登录状态
	 * 
	 * @param user
	 */
	public void saveLoginInfo(User user) {
		AppConfigService.putUser2Conf(this, user);
		mLoginStatus = true;
	}

	/**
	 * 清除用户登录信息
	 * 
	 * @param user
	 * @return
	 */
	public boolean clearLoginInfo(User user) {

		AppConfigService.clearUserInfo(getApplicationContext());
		mUser = null;
		mLoginStatus = false;
		return true;
	}

	/**
	 * 判断当前版本是否兼容目标版本的方法
	 * 
	 * @param VersionCode
	 * @return
	 */
	public static boolean isMethodsCompat(int VersionCode) {
		int currentVersion = android.os.Build.VERSION.SDK_INT;
		return currentVersion >= VersionCode;
	}

	/** 获取App安装包信息 */
	public PackageInfo getPackageInfo() {
		PackageInfo info = null;
		try {
			info = getPackageManager().getPackageInfo(getPackageName(), 0);
		} catch (NameNotFoundException e) {
			e.printStackTrace(System.err);
		}
		if (info == null)
			info = new PackageInfo();
		return info;
	}

	/** 获取当前版本名 */
	public String getVersionName() {
		return getPackageInfo().versionName;
	}

	/** 获取当前的版本 */
	public int getVersionCode() {
		return getPackageInfo().versionCode;
	}

	/**
	 * 初始化百度地图功能
	 * 
	 * @param context
	 */
	public void initEngineManager(Context context) {
		if (mBMapManager == null) {
			mBMapManager = new BMapManager(context);
		}

		if (!mBMapManager.init(new MyGeneralListener())) {
			Toast.makeText(AppApplication.getInstance().getApplicationContext(), "BMapManager  初始化错误!", Toast.LENGTH_LONG).show();
		}
	}

	/** 百度地图 常用事件监听，用来处理通常的网络错误，授权验证错误等 */
	public static class MyGeneralListener implements MKGeneralListener {

		@Override
		public void onGetNetworkState(int iError) {
			if (iError == MKEvent.ERROR_NETWORK_CONNECT) {
				Toast.makeText(AppApplication.getInstance().getApplicationContext(), "您的网络出错啦！", Toast.LENGTH_LONG).show();
			} else if (iError == MKEvent.ERROR_NETWORK_DATA) {
				Toast.makeText(AppApplication.getInstance().getApplicationContext(), "输入正确的检索条件！", Toast.LENGTH_LONG).show();
			}
			// ...
		}

		@Override
		public void onGetPermissionState(int iError) {
			// 非零值表示key验证未通过
			if (iError != 0) {
				// 授权Key错误：
				Toast.makeText(AppApplication.getInstance().getApplicationContext(),
						"请在 Application.java文件输入正确的授权Key,并检查您的网络连接是否正常！error: " + iError, Toast.LENGTH_LONG).show();
				AppApplication.getInstance().m_bKeyRight = false;
			} else {
				AppApplication.getInstance().m_bKeyRight = true;
				Toast.makeText(AppApplication.getInstance().getApplicationContext(), "key认证成功", Toast.LENGTH_LONG).show();
			}
		}
	}

	/**
	 * @ClassName: LoginTask
	 * @Description: 登录获取信息
	 * 
	 * @ModificationHistory
	 */
	private final class LoginTask extends AsyncTask<User, Integer, User> {

		@Override
		protected User doInBackground(User... params) {
			return UserService.login(params[0]);
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
		}

		@Override
		protected void onPostExecute(User result) {
			mUser = result;
		}

	}
}
